<template>
	<el-card>
		<div class="databaseDivClass">
			<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
				<el-form-item>
					<el-input v-model="state.queryForm.name" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item>
					<fast-select v-model="state.queryForm.databaseType" dict-type="database_type" placeholder="数据库类型" clearable></fast-select>
				</el-form-item>
				<el-form-item>
					<fast-select v-model="state.queryForm.dataType" dict-type="data_type" placeholder="数据源类型" clearable></fast-select>
				</el-form-item>
				<el-form-item>
					<el-input v-model="state.queryForm.databaseName" placeholder="库名(服务名)"></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="state.queryForm.databaseSchema" placeholder="schema"></el-input>
				</el-form-item>
				<el-form-item>
					<fast-select v-model="state.queryForm.status" dict-type="database_status" placeholder="状态" clearable></fast-select>
				</el-form-item>
				<!-- <el-form-item>
					<fast-select v-model="state.queryForm.isRtApprove" dict-type="yes_or_no" placeholder="是否支持实时接入" clearable></fast-select>
				</el-form-item> -->
				<!-- <el-form-item>
					<fast-project-select v-model="state.queryForm.projectId" placeholder="所属项目" clearable></fast-project-select>
				</el-form-item> -->
				<el-form-item>
					<el-button @click="getDataList()">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button v-auth="'data-integrate:database:save'" type="primary" @click="addOrUpdateHandle()">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button v-auth="'data-integrate:database:delete'" type="danger" @click="deleteBatchHandle()">删除</el-button>
				</el-form-item>
			</el-form>
			<el-table
				v-loading="state.dataListLoading"
				:data="state.dataList"
				border
				style="width: 100%"
				:height="cardDetailsTableHeight"
				@selection-change="selectionChangeHandle"
			>
				<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
				<el-table-column prop="name" label="名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
				<fast-table-column prop="databaseType" label="数据库类型" dict-type="database_type"></fast-table-column>
				<fast-table-column prop="dataType" label="数据源类型" width="110" dict-type="data_type"></fast-table-column>
				<fast-table-column prop="edgeIp" label="前置机主机ip" header-align="center" align="center" show-overflow-tooltip></fast-table-column>
				<fast-table-column prop="edgePort" label="前置机端口" header-align="center" align="center"></fast-table-column>
				<el-table-column prop="databaseIp" label="主机ip" header-align="center" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="databasePort" label="端口" header-align="center" align="center"></el-table-column>
				<el-table-column prop="databaseName" label="库名(服务名)" header-align="center" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="databaseSchema" label="schema" header-align="center" align="center" show-overflow-tooltip></el-table-column>
				<!-- <fast-table-column prop="status" label="状态" dict-type="database_status"></fast-table-column> -->
				<el-table-column label="状态" prop="status" header-align="center" align="center">
					<template #default="scope">
						<div class="status-item">{{ scope.row.status ? '正常' : '断开' }}<i :class="scope.row.status ? 'success-icon' : 'error-icon'"></i></div>
					</template>
				</el-table-column>
				<!-- <fast-table-project-column prop="projectId" label="所属项目" header-align="center" align="center"></fast-table-project-column> -->
				<fast-creator-column prop="creator" label="创建者" header-align="center" align="center"></fast-creator-column>
				<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="160" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
					<template #default="scope">
						<el-button v-auth="'data-integrate:database:update'" type="primary" link @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
						<el-button
							:disabled="!scope.row.status"
							:title="!scope.row.status ? '断开状态，不可查看库表' : ''"
							type="primary"
							link
							@click="tables(scope.row.id)"
							>库表</el-button
						>
						<el-button type="primary" link @click="test(scope.row)">测试</el-button>
						<el-button v-auth="'data-integrate:database:delete'" type="danger" link @click="deleteBatchHandle(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				:current-page="state.page"
				:page-sizes="state.pageSizes"
				:page-size="state.limit"
				:total="state.total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="sizeChangeHandle"
				@current-change="currentChangeHandle"
			>
			</el-pagination>

			<div class="drawerClass" style="height: 100%">
				<el-drawer
					style="padding: 0"
					v-model="state.drawer"
					show-close
					title="查看库表"
					size="100%"
					:before-close="drawerClose"
					:direction="state.direction"
				>
					<indexTwo v-if="state.drawer" :childProp="state.queryFormCheckId"></indexTwo>
					<el-button class="btnReturn" @click="btnReturnFun">返回</el-button>
				</el-drawer>
			</div>
		</div>

		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
	</el-card>
</template>

<script setup lang="ts" name="Data-integrateDatabaseIndex">
import { useCrud } from '@/hooks/indexZXQ.ts'
import { reactive, ref, computed, onMounted } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import indexTwo from './indexTwo.vue'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessage } from 'element-plus/es'
import { testOnline, getTablesById, getTableDataBySql } from '@/api/data-integrate/database'
import { ElLoading } from 'element-plus'

const state: IHooksOptions = reactive({
	dataListUrl: '/data-integrate/database/page',
	deleteUrl: '/data-integrate/database',
	queryFormCheckId: '',
	queryForm: {
		name: '',
		databaseType: '',
		databaseName: '',
		databaseSchema: '',
		status: '',
		isRtApprove: '',
		projectId: '',
		dataType: '' //数据源
	},
	drawer: false,
	direction: 'rtl',
	databaseId: '',
	sqlDataHeader: {},
	sqlData: [],
	tableData: [],
	dataSourceList: []
})

const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: number) => {
	addOrUpdateRef.value.init(id)
}

// 测试连接
const test = row => {
	const testLoading = ElLoading.service({
		lock: true,
		text: '连接测试中...... 请稍后',
		background: 'rgba(0, 0, 0, 0.7)'
	})
	testOnline(row)
		.then(() => {
			testLoading.close()
			setTimeout(() => {
				ElMessage.success({
					message: '测试连接成功',
					duration: 500,
					onClose: () => {
						getDataList()
					}
				})
			}, 100)
		})
		.catch(() => {
			testLoading.close()
			setTimeout(() => {
				getDataList()
			}, 500)
		})
}
const cardDetailsTableHeight: any = ref()
// 动态设置表格高度
const getCardDetailsTableHeight = () => {
	let tableH = 320 //距离页面下方的高度
	let tableHeightDetil = window.innerHeight - tableH
	if (tableHeightDetil <= 100) {
		cardDetailsTableHeight.value = 100
	} else {
		cardDetailsTableHeight.value = window.innerHeight - tableH
	}
}
// 监听窗口变化动态设置表格高度
window.onresize = () => {
	getCardDetailsTableHeight()
}
onMounted(() => {
	getCardDetailsTableHeight()
})
const tables = id => {
	state.drawer = true
	state.databaseId = id
	search.value = ''
	state.queryFormCheckId = id
	getTablesById(id).then(res => {
		state.tableData = res.data
	})
}

const sql = ref('')
const runSql = () => {
	if (!sql.value.trim()) {
		ElMessage.error('请输入sql')
		return
	}
	getTableDataBySql(state.databaseId, { sql: sql.value }).then(res => {
		state.sqlDataHeader = res.data.columns
		state.sqlData = res.data.rows
	})
}

const search = ref('')
const filterTableData = computed(() =>
	state.tableData.filter(
		data =>
			!search.value ||
			(data.tableName && data.tableName.toLowerCase().includes(search.value.toLowerCase())) ||
			(data.remarks && data.remarks.toLowerCase().includes(search.value.toLowerCase()))
	)
)

const drawerClose = (done: () => void) => {
	search.value = ''
	sql.value = ''
	state.sqlData = []
	state.sqlDataHeader = []
	state.tableData = []
	done()
}
const btnReturnFun = () => {
	search.value = ''
	sql.value = ''
	state.sqlData = []
	state.sqlDataHeader = []
	state.tableData = []
	state.drawer = false
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>

<style>
.databaseDivClass {
	height: calc(100vh - 170px);
	position: relative;
	overflow: hidden;
}
.databaseDivClass > .drawerClass > div {
	height: 100%;
	position: absolute !important;
	overflow: hidden;
}

.tableMain {
	width: 100%;
	display: flex;
	height: 100%;
}
.tableMain .tableLibrary {
	width: 33%;
	flex: 1;
}
.tableMain .tableSql {
	flex: 2;
	width: 66%;
}
.tableMain .tableSql .demo-tabs {
	height: 100%;
}
.tableMain .demo-tabs .el-tabs__content {
	height: calc(100% - 56px);
}
.tableMain .demo-tabs .el-tabs__content {
	height: calc(100% - 56px);
}
#pane-sqlConsole {
	height: 100%;
}
.tableMain .tableLibrary {
	height: calc(100% - 40px);
	overflow: auto;
}
.tableMain .tableLibrary .searchInput {
	margin: 0 15px;
	width: calc(100% - 30px);
}
/* 针对滚动条进行自定义 */
.tableMain .tableLibrary::-webkit-scrollbar {
	width: 6px; /* 设置滚动条的宽度 */
}
/* 设置滚动条轨道（track）的样式 */
.tableMain .tableLibrary::-webkit-scrollbar-track {
	background-color: #f5f5f5;
}

/* 设置滑块（thumb）的样式 */
.tableMain .tableLibrary::-webkit-scrollbar-thumb {
	background-color: #909399; /* 设置滑块的背景色为深灰色 */
	border-radius: 5px; /* 添加边角圆形效果 */
	/* opacity: 0.3; */
}
.btnReturn {
	position: absolute;
	top: 8px;
	right: 0;
}

.status-item {
	display: flex;
	align-items: center;
}
.success-icon {
	width: 20px;
	height: 20px;
	border-radius: 50%;
	background: rgba(81, 196, 27, 1);
	margin-left: 5px;
}

.error-icon {
	width: 20px;
	height: 20px;
	border-radius: 50%;
	background: rgba(245, 35, 45, 1);
	margin-left: 5px;
}
</style>
